package com.zsr.rabbitmq.five;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.zsr.rabbitmq.utils.RabbitMqUtils;
import org.apache.commons.io.FileUtils;

import java.io.File;

/**
 * 消息接收2 将消息写进文件
 * @author zsr
 * @date 2021/8/6 21:47
 */
public class ReceiveLogs02 {
    public static final String EXCHANGE_NAME="logs";

    public static void main(String[] args) throws Exception{
        Channel channel = RabbitMqUtils.getChannel();
        //声明一个交换机(生产者声明过可不声明)
        //channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
        /**
         * 生成一个临时的队列、队列的名字是随机的
         * 当消费者断开与队列的链接的时候 队列就自动删除
         * */
        String queueName = channel.queueDeclare().getQueue();
        /**
         * 绑定交换机和队列
         * 1.队列的名字
         * 2.交换机的名字
         * 3.routingKey
         */
        channel.queueBind(queueName,EXCHANGE_NAME,"");
        System.out.println("ReceiveLogs02等待接收消息，把接收到的消息打印在屏幕上...");

        DeliverCallback deliverCallback=(consumeTag,delivery)->{
            String message =new String(delivery.getBody(), "UTF-8");
            File file = new File("D:\\rabbitmq_info.txt");
            FileUtils.writeStringToFile(file,message,"UTF-8");
            System.out.println("数据写入文件成功:"+message);
        };
        channel.basicConsume(queueName,true,deliverCallback,consumeTag->{});

    }
}
